const Koa = require('koa');
const app = new Koa();
const views = require('koa-views');
const json = require('koa-json');
const onerror = require('koa-onerror');
const bodyparser = require('koa-bodyparser');
const logger = require('koa-logger');
const mongoose = require('mongoose');
const cors = require('koa2-cors'); //跨域处理
const sleep = require('./sleep');

// connect to mongodb
// const mongoose = require('mongoose')
// mongoose.connect('mongodb://localhost:27017/pt-admin');
// require('./app/model/mongodb/index');
// var isProduction = process.env.NODE_ENV === 'production';
// console.log("process.env.MONGODB_URI "+ process.env.MONGODB_URI );
// if(isProduction){
//   mongoose.connect(process.env.MONGODB_URI);
// } else {
  // mongoose.connect('mongodb://3.17.49.80:27017/pt-admin', {
  //   useNewUrlParser: true,
  //   useUnifiedTopology: true
  // });
(async ()=>{
  console.log("sleeping 3 seconds before connecting to mongodb...");
  await sleep(3000); // Jimmy Mo: sleep 3 seconds, let the docker init its network stack, otherwise, connecting to mongodb might throw error
  console.log("connecting to mongodb...");
  await mongoose.connect('mongodb://ptadmin:Slaj5WVdTnLPVXTb@dev-shard-00-00.azphn.mongodb.net:27017,dev-shard-00-01.azphn.mongodb.net:27017,dev-shard-00-02.azphn.mongodb.net:27017/pt-admin?ssl=true&replicaSet=atlas-pn5t9g-shard-0&authSource=admin&retryWrites=true&w=majority', {
    useNewUrlParser: true,
    useUnifiedTopology: true
  });
  console.log("mongodb connected...");
  console.log("Service started...");
})();

// }
// initialize routes
const index = require('./routes/index');

// error handler
onerror(app);

app.use(cors());
// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}));
app.use(json());
app.use(logger());
app.use(require('koa-static')(__dirname + '/public'));

app.use(views(__dirname + '/views', {
  extension: 'pug'
}));

// const PTCore = require('pt-core-common');
// (async() => {
//   await PTCore.rpc.serviceDiscoveryPolling.polling();
//   console.log(JSON.stringify(PTCore.rpc.serviceDiscoveryPolling.Services));
// })();

// logger
app.use(async (ctx, next) => {
  const start = new Date();
  await next();
  const ms = new Date() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
});

// routes
app.use(index.routes(), index.allowedMethods());

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx);
  console.log(err);
});

module.exports = app;